package org.emet.jee.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.security.util.StringSplitUtils;
import org.springframework.util.StringUtils;

public class EmetContext {

	private static Map<String, String> properties = loadEmetProps();

	private static Map<String, String> loadEmetProps() {
		Map<String, String> result = new HashMap<String, String>();

		try {
			result = loadProperties("/application.local.properties");
		} catch (Exception e) {
			result = loadProperties("/application.properties");
		}

		return result;
	}

	/**
	 * 获取common.properties中的某一配置项。
	 */
	public static String getProperty(String name, String defaultValue) {
		String value = (String) EmetContext.properties.get(name);
		if (value == null) {
			return defaultValue;
		}
		return value;
	}

	/**
	 * 获取common.properties中的某一配置项,
	 * 
	 * @param name
	 * @param defaultValue
	 * @return
	 */
	public static boolean getBoolProperty(String name, boolean defaultValue) {
		String value = (String) EmetContext.properties.get(name);
		if (value == null) {
			return defaultValue;
		}
		return "true".equals(value);
	}

	/**
	 * 根据参数path读取propertyes配置文件，path以'/'开始（即classpath的根）。
	 */
	public static Map<String, String> loadProperties(String path) {

		Map<String, String> map = new LinkedHashMap<String, String>();
		try {
			InputStream is = EmetContext.class.getResourceAsStream(path);
			Reader w = new InputStreamReader(is, "UTF-8");
			BufferedReader br = new BufferedReader(w);
			String line = br.readLine();
			while (line != null) {
				line = line.trim();
				if (!line.startsWith("#")) {
					String[] split = line.split("=");

					String name = "";
					String value = "";
					if (split.length > 2) {
						name = split[0];
						for (int i = 1; i < split.length; i++) {
							if (i == 1) {
								value += split[i];
							} else {
								value += "=" + split[i];
							}
						}
					} else {
						name = StringSplitUtils.substringBeforeLast(line, "=");
						value = StringSplitUtils.substringAfterLast(line, "=");
					}
					if (StringUtils.hasLength(name) && StringUtils.hasLength(value)) {
						map.put(name.trim(), value.trim());
					}
				}
				line = br.readLine();
			}
			return map;

		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
